module GYLite
{
			
						

	export class GYKeyboard
	{
		private static _instance:GYKeyboard;
		public static getInstance():GYKeyboard
		{
			return GYKeyboard._instance = GYKeyboard._instance || new GYKeyboard;
		}		
		private _keyListeners:IKeyBoardObject[];
		private _keyDownDict:Dictionary;
		private _typing:boolean;
		/**是否在输入框输入时仍然发出按键事件*/
		public keyEnabledWhenTyping:boolean;
		public constructor()
		{var s = this;
			s._keyDownDict = new Dictionary;
			s._keyListeners = new Array<IKeyBoardObject>();
			// GYSprite.stage.addEventListener(KeyboardEvent.KEY_DOWN, s.kDown, GYSprite.stage);
			document.addEventListener("keydown", function(e):void{s.kDown(e)});
			// GYSprite.stage.addEventListener(KeyboardEvent.KEY_UP, s.kUp, GYSprite.stage);
			document.addEventListener("keyup", function(e):void{s.kUp(e)});
		}
		public addKeyListener(k:IKeyBoardObject):void
		{var s = this;
			var tK:IKeyBoardObject;
			var ind:number=s._keyListeners.indexOf(k);
			if(ind > -1)
				s._keyListeners.splice(ind,1);
			s._keyListeners.push(k);				
			
		}
		public removeKeyListener(k:IKeyBoardObject):void
		{var s = this;
			var ind:number=s._keyListeners.indexOf(k);
			if(ind == -1)return;
			s._keyListeners.splice(ind,1);
		}
		private kDown(e:KeyboardEvent):void
		{var s = this;			
			var keyCode:number = e.keyCode;
			s._keyDownDict.setValue(keyCode, CommonUtil.loopTime);
			if(s._keyListeners.length == 0)return;
			if(s._typing && !s.keyEnabledWhenTyping)return;
			var len:number;
			var k:IKeyBoardObject;
			len = s._keyListeners.length;
			while(--len>-1)
			{
				k = s._keyListeners[len];
				if(k.disposed)
				{
					s._keyListeners.splice(len, 1);
					continue;
				}
				k.kDown(keyCode,e);
				if(k.keyFocus())break;
			}
		}
		private kUp(e:KeyboardEvent):void
		{var s = this;			
			var keyCode:number = e.keyCode;
			s._keyDownDict.setValue(keyCode, 0);
			if(s._keyListeners.length == 0)return;
			if(s._typing && !s.keyEnabledWhenTyping)return;
			var len:number;
			var k:IKeyBoardObject;			
			len = s._keyListeners.length;
			while(--len>-1)
			{
				k = s._keyListeners[len];
				if(k.disposed)
				{
					s._keyListeners.splice(len, 1);
					continue;
				}				
				k.kUp(keyCode,e);
				if(k.keyFocus())break;
			}
		}
		/**按下键的时间戳，0为未按下*/
		public isKeyDown(keyCode:number):number
		{var s = this;
			return s._keyDownDict.getValue(keyCode);
		}
		public releaseKey(keyCode:number):void
		{var s = this;
			if(keyCode == -1)
			{
				s._keyDownDict = new Dictionary;
				return;
			}
			s._keyDownDict.setValue(keyCode, 0);
		}
		
		public isCtrlDown():boolean
		{var s = this;
			return s._keyDownDict.getValue(Keyboard.CONTROL) > 0;	
		}
		public isAltDown():boolean
		{var s = this;
			return s._keyDownDict.getValue(Keyboard.ALTERNATE) > 0;
		}
		public isShiftDown():boolean
		{var s = this;
			return s._keyDownDict.getValue(Keyboard.SHIFT) > 0;
		}
		public isTyping(val:boolean):void
		{
			this._typing = val;
		}

	}
}